package sort;

/**
 * @author cxx
 * @create 2020-04-28 14:11
 **/
public class Sorts {

    public static void main(String[] args) {
        int[] arr = {9,6,18,62,21,2,1};
        insertSort (arr);
        for (int i : arr) {
            System.out.print (" "+i+" ");
        }
    }

    /**
     * 冒泡
     * 最好时间复杂度= O(n)
     * 最坏时间复杂度= O(n²)
     * @param arr
     */
    public static void bubbleSort(int[] arr){

        for (int i = 0; i < arr.length; i++) {
            boolean update = false;
            for (int j = 0; j < arr.length-1-i; j++) {
                if (arr[j] < arr[j+1]) {
                    int temp =arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                    update = true;
                }
            }
            if(!update){
                break;
            }
        }

    }


    public static void insertSort(int[] arr){
        for (int i = 1; i < arr.length; i++) {
            int val = arr[i];
            int index = i - 1;
            while (index >= 0 && arr[index] > val){
                arr[index + 1] = arr[index];
                index--;
            }
            arr[index + 1] = val;
        }
    }
}
